package managementSystem;

import java.io.*;
import java.util.HashMap;
import java.util.ArrayList;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 文件类
 */
@SuppressWarnings({"StringConcatenationInLoop", "unchecked"})
public class FileOperate {
    public void write(String path, ArrayList<HashMap<String, Object>> data) throws IOException {
        String dataStr = "";
        File file = new File(path);
        for(HashMap<String, Object> value : data){
            value.remove("people");
            dataStr += JSONObject.toJSONString(value) + "\n";
        }
        if (!file.exists()) {
            if(!file.createNewFile()){
                System.out.println("保存失败");
                return;
            }
        }
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write(dataStr);
        bw.flush();
        bw.close();
        System.out.println("保存成功");
    }

    public ArrayList<HashMap<String, Object>> reader(String path) throws IOException {
        String dataStr = "";
        File file = new File(path);
        ArrayList<HashMap<String, Object>> data = new ArrayList<>();
        if (!file.exists()) {
            System.out.println("文件不存在");
            return null;
        }
        BufferedReader br = new BufferedReader(new FileReader(file));
        while ((dataStr = br.readLine()) != null) {
            HashMap<String, Object> json = JSON.parseObject(dataStr, HashMap.class);
            if(json.get("grades") != null){
                json.put("grades", JSONObject.parseObject(((JSONObject)json.get("grades")).toString(), HashMap.class));
            }
            data.add(json);
        }
        br.close();
        return data;
    }
}
